/**
 * Created by daigou on 2015/5/29.
 */
var taobaoGetToken = require('./taobaoGetToken');
var config = require('./config.json');
var http = require('http');
var token = {
    sign: '',
    cookies: []
};

function getData(productId, pageNo, pageSize) {
    var data = {
        hasRateContent: 1,
        hasPic: 1,
        auctionNumId: productId,
        pageSize: pageSize,
        pageNo: pageNo,
        rateType: ''
    };

    return JSON.stringify(data);
}

function getQuery(obj) {
    var list = [];
    Object.getOwnPropertyNames(obj).forEach(function (key) {
        list.push(key + '=' + obj[key]);
    });
    return '?' + list.join('&');
}

function getToken(cookie, timespan, data) {
    return taobaoGetToken(cookie + "&" + timespan + "&" + config.appKey + "&" + data);
}

function getReview(productId, pageNo, callback) {
    var timespan = (new Date()).getTime();
    var data = getData(productId, pageNo, config.pageSize);
    var params = {
        v: '2.0',
        api: 'mtop.wdetail.getItemRates',
        appKey: config.appKey,
        t: timespan,
        type: 'json',
        sign: getToken(token.sign, timespan, data),
        data: encodeURIComponent(data)
    };
    var query = getQuery(params);

    var options = {
        hostname: config.hostname,
        path: config.path + query,
        headers: {
            Cookie: token.cookies.join(';')
        }
    };

    var request = http.request(options, function (res) {
        var data = '';
        res.setEncoding('utf-8');
        res.on('data', function (chunk) {
            data += chunk;
        }).on('end', function () {
            if (/FAIL_SYS_/m.test(data)) {
                console.log('start get taobao cookie from http header.');

                var cookiePattern = /^_m_h5_tk=([^\s_;]*)_/i;
                token.cookies.length = 0;
                res.headers['set-cookie'].forEach(function (item) {
                    var matches = cookiePattern.exec(item);
                    matches && matches.length && (token.sign = matches.pop());
                    token.cookies.push(item.split(';').shift());
                });

                console.log('get taobao cookie success.');

                //redo get for fail page
                getReview(productId, pageNo, callback);
            } else {
                data = JSON.parse(data).data;

                console.log('get %d taobao user reviews of page %d success,total:%d',
                    data.rateList ? data.rateList.length : 0, pageNo, data.total);

                (data.hasNext = pageNo < data.totalPage) && getReview(productId, ++pageNo, callback);
                callback && callback.call(null, data);
            }
        });

    }).on('error', function (e) {
        console.error('get taobao cookie error!' + e.message);
    });

    request.end();
}

module.exports = getReview;
